<template>
  <div class="data-export-container">
    <div class="export-section">
      <h3>数据导出</h3>
      <el-form :model="exportForm" label-width="120px">
        <!-- 导出类型选择 -->
        <el-form-item label="导出类型">
          <el-select v-model="exportForm.type" placeholder="请选择导出类型" style="width: 100%">
            <el-option-group label="借阅相关">
              <el-option label="用户借阅历史" value="user-borrow-history" />
              <el-option label="图书借阅记录" value="book-borrow-records" />
              <el-option label="逾期记录" value="overdue-records" />
            </el-option-group>
            <el-option-group label="统计分析">
              <el-option label="借阅趋势数据" value="borrowing-trend" />
              <el-option label="分类统计数据" value="category-stats" />
              <el-option label="热门图书数据" value="popular-books" />
              <el-option label="读者行为数据" value="reader-behavior" />
              <el-option label="库存状态数据" value="inventory-status" />
            </el-option-group>
            <el-option-group label="用户相关">
              <el-option label="用户信息" value="user-info" />
              <el-option label="用户活跃度" value="user-activity" />
            </el-option-group>
          </el-select>
        </el-form-item>

        <!-- 时间范围选择 -->
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="exportForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 用户选择（当选择用户相关数据时显示） -->
        <el-form-item label="用户选择" v-if="showUserSelect">
          <el-select
            v-model="exportForm.users"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入用户名搜索"
            :remote-method="handleUserSearch"
            :loading="userSearchLoading"
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.value"
              :label="user.label"
              :value="user.value"
            />
          </el-select>
        </el-form-item>

        <!-- 导出格式选择 -->
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="csv">CSV</el-radio>
            <el-radio label="pdf">PDF</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 导出按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleExport" :loading="exporting">
            <el-icon><Download /></el-icon>
            开始导出
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 导出历史记录 -->
    <div class="export-history">
      <h3>导出历史</h3>
      <el-table :data="exportHistory" style="width: 100%" max-height="400">
        <el-table-column prop="date" label="导出时间" width="180" />
        <el-table-column prop="type" label="导出类型" width="180" />
        <el-table-column prop="format" label="格式" width="100" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === '成功' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button 
              link 
              type="primary" 
              :disabled="row.status !== '成功'"
              @click="handleDownload(row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const exportForm = ref({
  type: '',
  timeRange: [],
  users: [],
  format: 'excel'
})

const exporting = ref(false)
const userSearchLoading = ref(false)
const userOptions = ref([])

// 计算是否显示用户选择
const showUserSelect = computed(() => {
  const userRelatedTypes = ['user-borrow-history', 'user-info', 'user-activity']
  return userRelatedTypes.includes(exportForm.value.type)
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    }
  }
]

// 模拟导出历史数据
const exportHistory = ref([
  {
    date: '2024-01-20 10:00:00',
    type: '用户借阅历史',
    format: 'Excel',
    status: '成功'
  },
  {
    date: '2024-01-19 15:30:00',
    type: '借阅趋势数据',
    format: 'PDF',
    status: '成功'
  },
  {
    date: '2024-01-18 09:15:00',
    type: '逾期记录',
    format: 'CSV',
    status: '失败'
  }
])

// 处理用户搜索
const handleUserSearch = async (query) => {
  if (query) {
    userSearchLoading.value = true
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      userOptions.value = [
        { value: '1', label: query + '_用户1' },
        { value: '2', label: query + '_用户2' },
        { value: '3', label: query + '_用户3' }
      ]
    } finally {
      userSearchLoading.value = false
    }
  } else {
    userOptions.value = []
  }
}

// 处理导出
const handleExport = async () => {
  if (!exportForm.value.type) {
    ElMessage.warning('请选择导出类型')
    return
  }
  if (!exportForm.value.timeRange || !exportForm.value.timeRange[0]) {
    ElMessage.warning('请选择时间范围')
    return
  }
  if (showUserSelect.value && exportForm.value.users.length === 0) {
    ElMessage.warning('请选择用户')
    return
  }

  exporting.value = true
  try {
    // 模拟导出过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 添加到导出历史
    exportHistory.value.unshift({
      date: new Date().toLocaleString(),
      type: exportForm.value.type,
      format: exportForm.value.format.toUpperCase(),
      status: '成功'
    })
    
    ElMessage.success('数据导出成功')
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  } finally {
    exporting.value = false
  }
}

// 处理下载
const handleDownload = (row) => {
  ElMessage.success('开始下载：' + row.type)
}

// 重置表单
const resetForm = () => {
  exportForm.value = {
    type: '',
    timeRange: [],
    users: [],
    format: 'excel'
  }
}
</script>

<style scoped>
.data-export-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.export-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.export-history {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #303133;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}
</style> 